package com.leetcode.partition1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/7/31 10:27
 */
public class LC77组合 {

    public static List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        backtrackingImprove(n, k, result, 1, new ArrayList<>());
        return result;
    }

    public static void main(String[] args) {
        System.out.println(combine(4, 2));
    }

    private static void backtrackingImprove(int n, int k, List<List<Integer>> result, int startIndex, List<Integer> subset) {
        if (subset.size() == k) {
            result.add(new ArrayList<>(subset));
            return;
        }
        //剪枝优化，如k=4，n=4，那么第一层for循环的时候，从元素2开始的遍历已经没有意义了；在第二层for循环，从元素3开始的遍历没有意义了
        //已经选择的元素个数：subset.size()   还需要的元素个数：k-subset.size()    在集合中至多要从起始位置n-(k-subset.size())+1开始遍历
        for (int i = startIndex; i <= n - (k - subset.size()) + 1; i++) {
            subset.add(i);
            backtrackingImprove(n, k, result, i + 1, subset);
            subset.remove(subset.size() - 1);
        }
    }

    private static void backtracking(int n, int k, List<List<Integer>> result, int startIndex, List<Integer> subset) {
        if (subset.size() == k) {           //选取的元素等于要求的个数，则遍历到叶子结点
            result.add(new ArrayList<>(subset));
            return;
        }
        for (int i = startIndex; i <= n; i++) {
            subset.add(i);
            backtracking(n, k, result, i + 1, subset);
            subset.remove(subset.size() - 1);
        }
    }
}
